package org.protester.base;

import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import junit.framework.TestCase;

@Entity
public class User extends EntityBase {

	@Column(nullable = false)
	private String username;

	@Column(nullable = false)
	private String password;

	public User() {
	}

	public User(String username, String password) {
		this.username = username;
		this.password = password;
		setDateCreated(new Date());
		setDateUpdated(getDateCreated());
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public static class Test extends TestCase {

		private EntityManagerFactory entityManagerFactory;

		protected void setUp() throws Exception {
			// like discussed with regards to SessionFactory, an
			// EntityManagerFactory is set up once for an application
			// IMPORTANT: notice how the name here matches the name we gave the
			// persistence-unit in persistence.xml!
			entityManagerFactory = Persistence
					.createEntityManagerFactory("org.protester.jpa");

		}

		@Override
		protected void tearDown() throws Exception {
			entityManagerFactory.close();
		}

		public void testBasicUsage() {
			// create a couple of events...
			EntityManager entityManager = entityManagerFactory
					.createEntityManager();
			entityManager.getTransaction().begin();
			entityManager.persist(new User("user1", "12345"));

			entityManager.getTransaction().commit();
			entityManager.close();

			// now lets pull events from the database and list them
			entityManager = entityManagerFactory.createEntityManager();
			entityManager.getTransaction().begin();
			List<User> result = entityManager.createQuery("from User",
					User.class).getResultList();
			for (User user : result) {
				System.out.println("User (" + user.getUsername() + ") : "
						+ user.getPassword());
			}
			entityManager.getTransaction().commit();
			entityManager.close();
		}

	}

}
